package com.oasis.oasislib.utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Pattern;

/**
 * Created by simaben on 7/8/16.
 */
public class StringUtils {

    private static final int W = 1000 * 10;

    public static String formatCount(String count) {
        double countD = Double.parseDouble(count);
        return formatCount(countD);
    }

    public static String formatCount(double count) {
        if (count < W) return ((int)count) + "";
        if (count % W == 0) return ((int)count / W) + "w";

        return ((int)Math.ceil(count / W)) + "w";
    }

    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static Pattern IMG_URL = Pattern
            .compile(".*?(gif|jpeg|png|jpg|bmp)");

    private final static Pattern URL = Pattern
            .compile("^(https|http)://.*?$(net|com|.com.cn|org|me|)");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        return toDate(sdate, dateFormater.get());
    }

    public static Date toDate(String sdate, SimpleDateFormat dateFormater) {
        try {
            return dateFormater.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String getDateString(Date date) {
        return dateFormater.get().format(date);
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = null;

        if (TimeZoneUtil.isInEasternEightZones())
            time = toDate(sdate);
        else
            time = TimeZoneUtil.transformTime(toDate(sdate),
                    TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());

        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天 ";
        } else if (days > 2 && days < 31) {
            ftime = days + "天前";
        } else if (days >= 31 && days <= 2 * 31) {
            ftime = "一个月前";
        } else if (days > 2 * 31 && days <= 3 * 31) {
            ftime = "2个月前";
        } else if (days > 3 * 31 && days <= 4 * 31) {
            ftime = "3个月前";
        } else {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }

    public static String friendly_time2(String sdate) {
        String res = "";
        if (isEmpty(sdate))
            return "";

        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        String currentData = StringUtils.getDataTime("MM-dd");
        int currentDay = toInt(currentData.substring(3));
        int currentMoth = toInt(currentData.substring(0, 2));

        int sMoth = toInt(sdate.substring(5, 7));
        int sDay = toInt(sdate.substring(8, 10));
        int sYear = toInt(sdate.substring(0, 4));
        Date dt = new Date(sYear, sMoth - 1, sDay - 1);

        if (sDay == currentDay && sMoth == currentMoth) {
            res = "今天 / " + weekDays[getWeekOfDate(new Date())];
        } else if (sDay == currentDay + 1 && sMoth == currentMoth) {
            res = "昨天 / " + weekDays[(getWeekOfDate(new Date()) + 6) % 7];
        } else {
            if (sMoth < 10) {
                res = "0";
            }
            res += sMoth + "/";
            if (sDay < 10) {
                res += "0";
            }
            res += sDay + " / " + weekDays[getWeekOfDate(dt)];
        }

        return res;
    }


    /**
     * 智能格式化
     */
    public static String friendly_time3(String sdate) {
        String res = "";
        if (isEmpty(sdate))
            return "";

        Date date = StringUtils.toDate(sdate);
        if (date == null)
            return sdate;

        SimpleDateFormat format = dateFormater2.get();

        if (isToday(date.getTime())) {
            format.applyPattern(isMorning(date.getTime()) ? "上午 hh:mm" : "下午 hh:mm");
            res = format.format(date);
        } else if (isYesterday(date.getTime())) {
            format.applyPattern(isMorning(date.getTime()) ? "昨天 上午 hh:mm" : "昨天 下午 hh:mm");
            res = format.format(date);
        } else if (isCurrentYear(date.getTime())) {
            format.applyPattern(isMorning(date.getTime()) ? "MM-dd 上午 hh:mm" : "MM-dd 下午 hh:mm");
            res = format.format(date);
        } else {
            format.applyPattern(isMorning(date.getTime()) ? "yyyy-MM-dd 上午 hh:mm" : "yyyy-MM-dd 下午 hh:mm");
            res = format.format(date);
        }
        return res;
    }

    /**
     * @return 判断一个时间是不是上午
     */
    public static boolean isMorning(long when) {
        android.text.format.Time time = new android.text.format.Time();
        time.set(when);

        int hour = time.hour;
        return (hour >= 0) && (hour < 12);
    }

    /**
     * @return 判断一个时间是不是今天
     */
    public static boolean isToday(long when) {
        android.text.format.Time time = new android.text.format.Time();
        time.set(when);

        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;

        time.set(System.currentTimeMillis());
        return (thenYear == time.year)
                && (thenMonth == time.month)
                && (thenMonthDay == time.monthDay);
    }

    /**
     * @return 判断一个时间是不是昨天
     */
    public static boolean isYesterday(long when) {
        android.text.format.Time time = new android.text.format.Time();
        time.set(when);

        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;

        time.set(System.currentTimeMillis());
        return (thenYear == time.year)
                && (thenMonth == time.month)
                && (time.monthDay - thenMonthDay == 1);
    }

    /**
     * @return 判断一个时间是不是今年
     */
    public static boolean isCurrentYear(long when) {
        android.text.format.Time time = new android.text.format.Time();
        time.set(when);

        int thenYear = time.year;

        time.set(System.currentTimeMillis());
        return (thenYear == time.year);
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static int getWeekOfDate(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return w;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.get().format(today);
            String timeDate = dateFormater2.get().format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 返回long类型的今天的日期
     *
     * @return
     */
    public static long getTodayLong() {
        Calendar cal = Calendar.getInstance();
        String curDate = dateFormater2.get().format(cal.getTime());
        curDate = curDate.replace("-", "");
        return Long.parseLong(curDate);
    }


    /**
     * 返回long类型的今天的日期
     *
     * @return
     */
    public static String getTodayStr() {
        Calendar cal = Calendar.getInstance();
        String curDate = dateFormater2.get().format(cal.getTime());
        return curDate;
    }


    public static String getCurTimeStr() {
        Calendar cal = Calendar.getInstance();
        String curDate = dateFormater.get().format(cal.getTime());
        return curDate;
    }

    /***
     * 计算两个时间差，返回的是的秒s
     *
     * @param dete1
     * @param date2
     * @return
     * @author 火蚁 2015-2-9 下午4:50:06
     */
    public static long calDateDifferent(String dete1, String date2) {

        long diff = 0;

        Date d1 = null;
        Date d2 = null;

        try {
            d1 = dateFormater.get().parse(dete1);
            d2 = dateFormater.get().parse(date2);

            // 毫秒ms
            diff = d2.getTime() - d1.getTime();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return diff / 1000;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 判断一个url是否为图片url
     *
     * @param url
     * @return
     */
    public static boolean isImgUrl(String url) {
        if (url == null || url.trim().length() == 0)
            return false;
        return IMG_URL.matcher(url).matches();
    }

    /**
     * 判断是否为一个合法的url地址
     *
     * @param str
     * @return
     */
    public static boolean isUrl(String str) {
        if (str == null || str.trim().length() == 0)
            return false;
        return URL.matcher(str).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    public static String getString(String s) {
        return s == null ? "" : s;
    }

    /**
     * 将一个InputStream流转换成字符串
     *
     * @param is
     * @return
     */
    public static String toConvertString(InputStream is) {
        StringBuffer res = new StringBuffer();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader read = new BufferedReader(isr);
        try {
            String line;
            line = read.readLine();
            while (line != null) {
                res.append(line + "<br>");
                line = read.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != isr) {
                    isr.close();
                    isr.close();
                }
                if (null != read) {
                    read.close();
                    read = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
            }
        }
        return res.toString();
    }

    /***
     * 截取字符串
     *
     * @param start 从那里开始，0算起
     * @param num   截取多少个
     * @param str   截取的字符串
     * @return
     */
    public static String getSubString(int start, int num, String str) {
        if (str == null) {
            return "";
        }
        int leng = str.length();
        if (start < 0) {
            start = 0;
        }
        if (start > leng) {
            start = leng;
        }
        if (num < 0) {
            num = 1;
        }
        int end = start + num;
        if (end > leng) {
            end = leng;
        }
        return str.substring(start, end);
    }

    /**
     * 获取当前时间为每年第几周
     *
     * @return
     */
    public static int getWeekOfYear() {
        return getWeekOfYear(new Date());
    }

    /**
     * 获取当前时间为每年第几周
     *
     * @param date
     * @return
     */
    public static int getWeekOfYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        int week = c.get(Calendar.WEEK_OF_YEAR) - 1;
        week = week == 0 ? 52 : week;
        return week > 0 ? week : 1;
    }

    public static int[] getCurrentDate() {
        int[] dateBundle = new int[3];
        String[] temp = getDataTime("yyyy-MM-dd").split("-");

        for (int i = 0; i < 3; i++) {
            try {
                dateBundle[i] = Integer.parseInt(temp[i]);
            } catch (Exception e) {
                dateBundle[i] = 0;
            }
        }
        return dateBundle;
    }

    /**
     * 返回当前系统时间
     */
    public static String getDataTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }

    public static CharSequence getTouchUrlWithoutHttp() {
        return "http:www.baidu.com";
    }

    public static CharSequence getTestTouchUrlWithoutHttp() {
        return "http:www.baidu.com";
    }

    public static List<String> get100Years() {
        int year = getCurrentDate()[0];
        List<String> years = new ArrayList<>();
        years.add(year + "");
        for (int i = 0; i < 100; i++) {
            if (year > 0)
                years.add(String.valueOf(year - i));
        }
        return years;
    }


    public static List<String> get12Months() {
        List<String> months = new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            if (i > 0)
                months.add(String.format("%02d", i));
        }
        return months;
    }


    public static List<String> getDayOfMonth(int year, int month) {
        Calendar cl = Calendar.getInstance();//实例化一个日历对象
        cl.set(Calendar.YEAR, year);
        cl.set(Calendar.MONTH, month);
        int dayCount = cl.getActualMaximum(Calendar.DATE);//得到一个月最大的一天就是一个月多少天
        List<String> days = new ArrayList<>();
        for (int i = 1; i < dayCount; i++) {
            if (i > 0)
                days.add(String.format("%02d", i));
        }
        return days;
    }

    /**
     * StringUtil.isEmpty(null) = true StringUtil.isEmpty("") = true
     * StringUtil.isEmpty(" ") = false StringUtil.isEmpty("hlx") = false
     * StringUtil.isEmpty("  hlx  ") = false
     */
    // 是否为空
    public static boolean isEmpty(String str) {
        return (str == null || str.length() == 0);
    }

    /**
     * StringUtil.isBlank(null) = true StringUtil.isBlank("") = true
     * StringUtil.isBlank(" ") = true StringUtil.isBlank("hlx") = false
     * StringUtil.isBlank("  hlx  ") = false
     */
    // 是否为空白
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    /**
     * StringUtil.isNotEmpty(null) = false StringUtil.isNotEmpty("") = false
     * StringUtil.isNotEmpty(" ") = true StringUtil.isNotEmpty("hlx") = true
     * StringUtil.isNotEmpty("  hlx  ") = true
     */
    // 是否不为空
    public static boolean isNotEmpty(String str) {
        return (str != null && str.length() > 0);
    }

    /**
     * StringUtil.isNotBlank(null) = false StringUtil.isNotBlank("") = false
     * StringUtil.isNotBlank(" ") = false StringUtil.isNotBlank("hlx") =
     * true StringUtil.isNotBlank("  hlx  ") = true
     */
    // 是否不为空白
    public static boolean isNotBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return false;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return true;
            }
        }
        return false;
    }

    /**
     * StringUtil.isNumeric(null) = false StringUtil.isNumeric("") = false
     * StringUtil.isNumeric("  ") = false StringUtil.isNumeric("1234567890") =
     * true StringUtil.isNumeric("12 3") = false StringUtil.isNumeric("ab2c") =
     * false StringUtil.isNumeric("12-3") = false StringUtil.isNumeric("12.3") =
     * false
     */
    // 是否为数字
    public static boolean isNumeric(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }

    // 分割字符串
    public static String[] split(String src, String separator) {
        if (src == null || separator == null) {
            return null;
        }
        if (src.length() == 0 || separator.length() == 0) {
            String[] s = {src};
            return s;
        }
        java.util.Vector<String> v = new java.util.Vector<String>();
        int start = 0, end = 0;
        while ((end = src.indexOf(separator, start)) != -1) {
            v.addElement(src.substring(start, end));
            start = end + separator.length();
        }
        v.addElement(src.substring(start));
        int ilen = v.size();
        if (ilen < 1) {
            return null;
        }
        String[] arr = new String[ilen];
        for (int i = 0; i < ilen; i++) {
            arr[i] = v.elementAt(i).toString();
        }
        return arr;
    }

    // 获取url最后一节
    public static String getLastPathComponent(String url) {
        if (url == null)
            return "";
        return url.split("/")[url.split("/").length - 1];
    }

    // 是否是子字符串
    public static boolean isSubString(String str, String subStr) {
        return str.indexOf(subStr) != -1;
    }

    public static void appendString(StringBuffer buff, String str) {
        if (isBlank(str))
            str = "";
        buff.append(str);
    }

    // 字符串拼接
    public static String appendString(String str1, String str2) {
        if (isBlank(str1))
            str1 = "";
        StringBuffer strBuf = new StringBuffer(str1);
        appendString(strBuf, str2);
        return strBuf.toString();
    }

    public static boolean isNotBlank(Object object) {
        return !isBlank(object);
    }

    public static boolean isNull(Object object) {
        return object == null;
    }

    public static boolean isNotNull(Object object) {
        return !isNull(object);
    }

    public static boolean isBlank(Object object) {
        if (isNull(object))
            return true;
        if (object instanceof JSONArray) {
            JSONArray obj = (JSONArray) object;
            if (obj.length() == 0)
                return true;
        }
        if (object instanceof JSONObject) {
            JSONObject obj = (JSONObject) object;
            if (obj.length() == 0)
                return true;
        }
        if (object instanceof List) {
            List<?> obj = (List<?>) object;
            if (obj.size() == 0)
                return true;
        }
        if (object instanceof Map) {
            Map<?, ?> obj = (Map<?, ?>) object;
            if (obj.size() == 0)
                return true;
        }
        return isNull(object);
    }


    public static String str2MD5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] b = md.digest(str.getBytes("utf-8"));
            return byte2HexStr(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String byte2HexStr(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; ++i) {
            String s = Integer.toHexString(b[i] & 0xFF);
            if (s.length() == 1)
                sb.append("0");

            sb.append(s.toUpperCase());
        }
        //System.out.println("md5: " + sb.toString());
        return sb.toString();
    }


    public static List<String> getParameterKeys(Map<String, String> params) {
        List<String> keys = new ArrayList<String>();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                keys.add(entry.getKey());
            }
        }
        return keys;
    }

    public static List<String> getParameterValues(Map<String, String> params) {
        List<String> keys = new ArrayList<String>();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                keys.add(entry.getValue());
            }
        }
        return keys;
    }

    public static String getParameterKey(Map<String, String> params, String value) {
        String key = null;
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (entry.getValue().equals(value)) {
                    key = entry.getKey();
                    break;
                }
            }
        }
        return key;
    }

    public static boolean hasParameter(Map<Integer, String> params, int key, String value) {
        boolean has;
        if (params != null && params.size() > 0 && value != null) {
            if (params.containsKey(key) && value.equals(params.get(key))) {
                has = true;
            } else {
                has = false;
            }
        } else {
            has = false;
        }
        return has;
    }

    /**
     * 判断数字
     */
    public static boolean isNumber(String str) {
        return str.matches("0(\\.\\d+$)+|^0$|^[1-9]\\d*(\\.\\d+$){0,1}");
    }

    /**
     * 判断是否为非负数
     *
     * @param str
     * @return
     */
    public static boolean isPositiveRationalNumber(String str) {
        return str.matches("^\\d+(\\.\\d+)?$");
    }

    /**
     * 正整数
     *
     * @param str
     * @return
     */
    public static boolean isPositiveNumber(String str) {
        return str.matches("^[1-9]\\d*$");
    }

    /**
     * 去除所有空格
     */
    public static String nullSpaceStr(String str) {
        String nullSpaceStr = str.replace(" ", "");
        return nullSpaceStr;
    }

    public static boolean containsBlack(String str) {
        return str.contains(" ");
    }

    /**
     * 校验str
     */
    public static boolean checkString(String source, String reg) {
        return source.matches(reg);
    }

    /**
     * 校验 <html>
     */
    public static boolean containsHtml(String content) {
        if (content.indexOf("<html") > 0) {
            return true;
        }
        return false;
    }

    /**
     * 格式化用户名
     */
    public static String getFormatUserName(String userName) {
        String formatString = null;
        try {
            formatString = userName.substring(0, 2) + "****" + userName.substring(userName.length() - 2, userName.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == formatString) {
            formatString = "";
        }

        return formatString;
    }

    /**
     * 格式化用户名
     */
    public static String getBindCardUserName(String userName) {
        String formatString = null;
        try {
            formatString = "*" + userName.substring(1, userName.length());

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == formatString) {
            formatString = "";
        }

        return formatString;
    }

    /**
     * 手机号加密
     */
    public final static String encryptPhoneNum(String phoneNum) {
        String phoneNum1 = phoneNum.substring(0, 3);
        String pnoneNum2 = phoneNum.substring(phoneNum.length() - 4, phoneNum.length());
        String newPhoneNum = phoneNum1 + "****" + pnoneNum2;
        return newPhoneNum;
    }

    public static String getFromatBankCard(String cardid) {
        StringBuilder resultBuilder = new StringBuilder();
        String part1 = cardid.substring(0, 4);
        String part2 = cardid.substring(4, cardid.length());
        resultBuilder.append(part1);
        for (int i = 0; i < part2.length(); i++) {
            resultBuilder.append("*");
        }
        return resultBuilder.toString();
    }

    /**
     * 截取字符串
     * boolean inEllipsis是判断截取后的字符串后面是否add...
     */
    public static String CutOutStr(String str, int cutoutNum, boolean inEllipsis) {
        if (str != null && str.length() > 0) {
            if (str.length() <= cutoutNum) {
                return str;
            } else {
                String newStr = str.substring(0, cutoutNum);
                if (inEllipsis) {
                    newStr = newStr + "...";
                    return newStr;
                }
                return newStr;
            }
        }
        return null;
    }

    public static String formatNum4(String str) {
        return new DecimalFormat("##0.0000").format(new Double(str));
    }

    public static String formatDate(String dataString) {
        StringBuilder sb = new StringBuilder(dataString);
        return sb.insert(4, "-").insert(7, "-").toString();
    }

    public static boolean isTrue(String json) {
        return Boolean.valueOf(json);
    }


    /**
     * 判断条件为，开头字母为1，长度为11位
     *
     * @param number
     * @return
     */
    public static boolean isPhoneNumber(String number) {
        return number.matches("^[1][0-9]{10}$");
    }

    public static boolean isPostNumber(String number) {
        return number.matches("^[0-9]{6}$");
    }

    /**
     * 整数部分不超过10位，小数点后2位
     *
     * @param number
     * @return
     */
    public static boolean is2EndNumber(String number) {
        return number.matches("^\\d{0,8}\\.{0,1}(\\d{1,2})?$");
    }

    //数字字母验证
    public static boolean isLoginName(String name) {
        String userNameRegex = "[a-z0-9A-Z.,/@]{6,16}";
        return name.matches(userNameRegex);
    }

    //姓名验证
    public static boolean isChineseName(String name) {
        String chineseRegex = "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$";
        return name.matches(chineseRegex);
    }

    //身份证号码验证
    public static boolean isIdCard(String idCard) {
        String idCardeNoRegex = "(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
        return idCard.matches(idCardeNoRegex);
    }

    //银行卡号验证
    public static boolean isBankNum(String bankNum) {
        String cardNumRegex = "^[0-9]{15,19}$";
        return bankNum.matches(cardNumRegex);
    }

    //手机号验证
    public static boolean isPhoneNum(String phoneNum) {
        String phoneRegex = "^[1][0-9]{10}$";
        return phoneNum.matches(phoneRegex);
    }

    private final static int[] dayArr = new int[]{20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22};
    private final static String[] constellationArr = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"};

    /**
     * 根据月，日获得星座
     *
     * @param month
     * @param day
     * @return
     */
    public static String getConstellation(int month, int day) {
        return day < dayArr[month - 1] ? constellationArr[month - 1] : constellationArr[month];
    }
}
